<template>
  <div class="carousel">
    <div class="slides" :style="{ transform: `translateX(-${currentIndex * 100}%)` }">
      <div v-for="(slide, index) in slides" :key="index" class="slide">
        <img :src="slide.image" alt="slide">
      </div>
    </div>
    <!-- 将列表放在轮播图内 -->
    <div class="list-container">
      <ListIn :title="listTitle" :items="listItems" />
    </div>
    <div class="indicators">
      <span
        v-for="(slide, index) in slides"
        :key="index"
        :class="{ active: index === currentIndex }"
        @click="goToSlide(index)"
      ></span>
    </div>
  </div>
</template>

<script>
import { ref, watch, onMounted } from 'vue'
import ListIn from './ListIn.vue'

export default {
  name: 'BannerCarousel',
  components: {
    ListIn
  },
  props: {
    slides: Array,
    interval: {
      type: Number,
      default: 3000
    },
    listTitle: String,
    listItems: Array
  },
  setup(props) {
    const currentIndex = ref(0);

    const nextSlide = () => {
      currentIndex.value = (currentIndex.value + 1) % props.slides.length;
    };

    const prevSlide = () => {
      currentIndex.value = (currentIndex.value - 1 + props.slides.length) % props.slides.length;
    };

    const goToSlide = (index) => {
      currentIndex.value = index;
    };

    let intervalId;

    const startAutoSlide = () => {
      intervalId = setInterval(nextSlide, props.interval);
    };

    const stopAutoSlide = () => {
      clearInterval(intervalId);
    };

    onMounted(() => {
      startAutoSlide();
    });

    watch(currentIndex, () => {
      stopAutoSlide();
      startAutoSlide();
    });

    return { currentIndex, nextSlide, prevSlide, goToSlide };
  }
};
</script>

<style scoped>
.carousel {
  position: relative;
  width: 1900px; /* 设置宽度为固定值 */
  height: 380px; /* 设置高度为固定值 */
  overflow: hidden;
  margin: 0 auto;
}

.slides {
  display: flex;
  transition: transform 0.5s ease;
}

.slide {
  flex: 0 0 100%;
}

img {
  width: 100%;
  height: auto;
}

.indicators {
  position: absolute;
  bottom: 10px;
  left: 50%;
  transform: translateX(-50%);
}

.indicators span {
  width: 12px; /* 使用vw单位 */
  height: 12px; /* 使用vw单位 */
  border-radius: 50%;
  background-color: rgba(51, 51, 51, 0.5); /* 设置透明度为50% */
  margin: 0 5px;
  cursor: pointer;
  display: inline-block;
}

.indicators .active {
  background-color: #007aff;
}
</style>
